package com.settlement.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.model.entity.NoMatchRecord;
import com.settlement.system.service.NoMatchRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import com.settlement.system.model.query.NoMatchRecordQuery;
import com.settlement.system.model.form.NoMatchRecordForm;
import org.springdoc.core.annotations.ParameterObject;
import io.swagger.v3.oas.annotations.Parameter;
import com.settlement.system.model.vo.NoMatchRecordImportVo;
import com.settlement.system.listener.easyexcel.NoMatchRecordListener;
import com.alibaba.excel.EasyExcel;

import com.alibaba.excel.EasyExcelFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 转换不到账单记录表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-08-09
 */
@RestController
@RequestMapping("/api/v1/noMatchRecord")
@RequiredArgsConstructor
public class NoMatchRecordController {

    private final NoMatchRecordService noMatchRecordService;

    @GetMapping("/page")
    public PageResult<NoMatchRecord> getPage(@ParameterObject NoMatchRecordQuery queryParams) {
        Page<NoMatchRecord> result = noMatchRecordService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存转换不到账单记录表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:save')")
    public Result<?> saveNoMatchRecord(@RequestBody @Valid NoMatchRecordForm noMatchRecordForm) {
        boolean result = noMatchRecordService.saveNoMatchRecord(noMatchRecordForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取转换不到账单记录表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<NoMatchRecordForm> getNoMatchRecordFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        NoMatchRecordForm noMatchRecord = noMatchRecordService.getNoMatchRecordFormData(id);
        return Result.success(noMatchRecord);
    }

    @Operation(summary = "删除转换不到账单记录表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:delete')")
    public Result<?> deleteNoMatchRecord(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = noMatchRecordService.deleteNoMatchRecord(ids);
        return Result.judge(result);
    }

    @Operation(summary = "重新转换原始账单", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/reBill")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:reBill')")
    public Result<?> reBill(@RequestParam("ids") String ids) {
        noMatchRecordService.reBill(ids);
        return Result.success();
    }

    @Operation(summary = "忽略原始账单", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/ignore")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:ignore')")
    public Result<?> ignore(@RequestParam("ids") String ids) {
        noMatchRecordService.ignore(ids);
        return Result.success();
    }

    @Operation(summary = "根据查询结果全部转换", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/reBillAll")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:reBillAll')")
    public Result<?> reBillAll(@ParameterObject NoMatchRecordQuery queryParams) {
        noMatchRecordService.reBillAll(queryParams);
        return Result.success();
    }

    @Operation(summary = "类似天猫资金流水的账单，回炉重造功能", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/fallback")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:fallback')")
    public Result<?> fallback(@ParameterObject NoMatchRecordQuery queryParams) {
        Assert.notNull(queryParams.getBillType(), "账单类型不能为空");
        noMatchRecordService.fallback(queryParams);
        return Result.success();
    }

    @Operation(summary = "转换不到账单记录表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/noMatchRecordImport")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:import')")
    @PreventDuplicateSubmit
    public Result<?> noMatchRecordImport(@RequestParam("file") MultipartFile file) throws Exception {
        NoMatchRecordListener listener = new NoMatchRecordListener();
        EasyExcelFactory.read(file.getInputStream(), NoMatchRecordImportVo.class, listener).sheet(0).doRead();
        List<NoMatchRecordImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        noMatchRecordService.importData(list);
        return Result.success();
    }

    @Operation(summary = "查看原始数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/getDataInfo/{id}")
    public Result<?> getDataInfo(@Parameter(description = "主键ID") @PathVariable Long id) {
        String result = noMatchRecordService.getDataInfo(id);
        return Result.success(result);
    }

    @Operation(summary = "导出转换不到账单记录表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:noMatchRecord:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "转换不到账单记录表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<NoMatchRecordImportVo> noMatchRecordList = noMatchRecordService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), NoMatchRecordImportVo.class).sheet("转换不到账单记录表").doWrite(noMatchRecordList);
    }
}

